import React, {PureComponent, Fragment} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
  Button,
  Menu,
  Modal,
  Form,
  message,
  Table,
  DatePicker,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find'
import AddOrEditUser from './AddOrEditUser'
import debounce from 'lodash/debounce'
import {ellipsis} from '@/utils/utils';
import DetailInfo from './Info'
const FormItem = Form.Item;
import {routerRedux} from 'dva/router';
@connect(({notices, loading}) => ({
  notices,
  loading: loading.models.notices,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, {name: 'user_add_and_edit'}),
      showdelBtn: find(this.permissions, {name: 'user_delete'}),
      showPasswordBtn: find(this.permissions, {name: 'user_default_password_edit'}),
      user_password_reset: find(this.permissions, {name: 'user_password_reset'}),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {
    this.changeTableY()
    const {dispatch} = this.props;
    const {
      notices: {pageLoaded, scrollData},
    } = this.props;
    console.log('pageLoaded', pageLoaded)
    const table = document.querySelector('.ant-table-body')
    if (pageLoaded) {
      setTimeout(function () {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0)

    } else {
      const {
        notices: {searchParams},
      } = this.props;
      console.log('searchParams', searchParams)
      dispatch({
        type: 'notices/fetch',
        payload: searchParams,
        callback: ()=> {
          const {dispatch} = this.props;
          dispatch({
            type: 'notices/changeLoaded',
          })
        }
      });
    }

    window.addEventListener('resize', this.resize)
    table.addEventListener('scroll', debounce(this.scroll, 150))
  }

  scroll = (e)=> {
    const {dispatch} = this.props;
    dispatch({
      type: 'notices/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop
      },
    })
  }
  resize = ()=> {
    this.changeTableY()
  }
  changeTableY = ()=> {
    this.setState({
      tableY: document.querySelector('.table-pagination').getBoundingClientRect().top -
      document.querySelector('.custom-small-table').getBoundingClientRect().top - 50
    })
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
    window.removeEventListener('resize', this.resize)
    const table = document.querySelector('.ant-table-body')
    table.removeEventListener('scroll', debounce(this.scroll, 300))
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values)
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'notices/fetch',
      payload: {
        ...values,
      },
      callback: function () {
        console.log('handleSearch callback')
        if (cb) cb()
      }
    });
  }

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
      notices: {searchParams},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'开始时间'}>
          {getFieldDecorator('started_at', {
            initialValue: moment(searchParams.started_at),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label={'结束时间'}>
          {getFieldDecorator('ended_at', {
            initialValue: moment(searchParams.ended_at),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem >
          <Button type="primary" icon='search' onClick={()=> {
            const {form} = this.props;
            form.validateFields((err, fieldsValue) => {
              if (err) return;

              this.handleSearch({
                page: 1,
                per_page: this.state.per_page,
                ...fieldsValue,
                started_at: moment(fieldsValue.started_at).format('YYYY-MM-DD'),
                ended_at: moment(fieldsValue.ended_at).format('YYYY-MM-DD'),
              })

            });
          }}>
            查询
          </Button>
          <Button style={{marginLeft: 8}} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          <Button icon="plus" style={{marginLeft: 8}} type="primary" onClick={
            ()=> {
              this.setState({
                addModal: true
              })
            }
          }>
            发布通知
          </Button>

        </FormItem>

      </Form>
    );
  }
  handleAdd = ()=> {
    const formValues = this.AddUser.props.form.getFieldsValue();
    console.log('formValues', formValues)
    const that = this;
    this.props.dispatch({
      type: 'notices/add',
      payload: {
        ...formValues,
        distributor_ids:formValues.distributor_ids?formValues.distributor_ids.reduce((pre,item)=>{
          pre.push(item.key)
          return pre
        },[]):[],
        date:moment(formValues.date).format('YYYY-MM-DD')
      },
      callback: function () {
        message.success('发布通知成功')
        that.setState({
          addModal: false,
        });
        const {
          notices: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      started_at: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD').format('YYYY-MM-DD'),
      ended_at: moment(new Date(), 'YYYY-MM-DD').format('YYYY-MM-DD'),
      page: 1,
      per_page: 30,
    })
  }

  render() {
    const {
      notices: {data, loading, meta, searchParams, selectedRowKeys},
    } = this.props;
    const {
      form: {getFieldDecorator},
    } = this.props;
    const renderMenu = (record) => (
      <Menu onClick={(e)=>this.handleMenuClick(e, record)} selectedKeys={[]}>
        {this.state.user_password_reset && (record.protection_level === 1 || record.protection_level === 3) &&
        <Menu.Item key="reset">重置密码</Menu.Item>}
        {this.state.showdelBtn && record.protection_level !== 2 && <Menu.Item key="delete">删除</Menu.Item>}
      </Menu>
    );
    const columns = [
      {
        title: '日期',
        width: 100,
        dataIndex: 'date',
        render: (val, record)=> {
          return ellipsis(val, 100)
          // return <div onClick={()=>{
          //   const {dispatch} = this.props;
          //   dispatch(routerRedux.push('/notices/123'));
          // }
          // }>点击</div>
        }
      },
      {
        title: '项目名称',
        width: 150,
        dataIndex: 'project_name',
        render: (val, record)=> {
          return ellipsis(val, 150)
        }
      },
      {
        title: '标题',
        width: 150,
        dataIndex: 'title',
        render: (val, record)=> {
          return ellipsis(val, 150)
        }
      },
      {
        title: '内容',
        dataIndex: 'content',
        width: 200,
        render: (val, record)=> {
          return ellipsis(val, 200)
        }
      },
      {
        title: '创建时间',
        dataIndex: 'created_at',
        width: 150,
        render: (val, record)=> {
          return ellipsis(val, 150)
        }
      },
      {
        title: '发送方式',
        dataIndex: 'send_type',
        render: (val, record)=> {
          return val===1?'全部发送':'指定分销商发送'
        }
      },
      {
        title: '操作',
        width: 140,
        fixed:'right',
        render: (val, record, index) =>{
          return   record.send_type===2&& <Fragment>
            <Button type="primary"  size="small" onClick={(e)=> {
              e.stopPropagation()
              this.setState({
                editRecord: record,
                editModal: true
              })
            }
            }>查看发送分销商</Button>
          </Fragment>
        }
      },
    ];
    const rowSelection = {
      columnWidth: 40,
      selectedRowKeys,
      columnTitle: ' ',
      onChange: (selectedRowKeys) => {
        this.props.dispatch({
          type: 'notices/changeSelectRow',
          payload: selectedRowKeys,
        })
      },
    };
    return <div className="custom-card">
      <div className="table-title">群发通知</div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <Table
          style={{color: '#fff'}}
          className="custom-small-table"
          loading={loading}
          rowKey={'id'}
          dataSource={data}
          columns={columns}
          pagination={false}
          size="small"
          scroll={{x: 1200, y: this.state.tableY}}
          rowSelection={rowSelection}
          onRow={(record) => ({
            onClick: () => {
              this.props.dispatch({
                type: 'notices/selectRow',
                payload: record,
              })
            },
          })}
        />

      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{...searchParams}} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={'发布通知'}
        visible={this.state.addModal}
        centered
        onCancel={()=> {
          this.setState({addModal: false})
        }}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddUser = inst}/>

      </Modal>
      <Modal
        title={''}
        destroyOnClose
        visible={this.state.editModal}
        centered
        footer={null}
        width={600}
        onCancel={()=> {
          this.setState({editModal: false})
        }}
      >
        <DetailInfo {...this.state.editRecord}/>

      </Modal>
    </div>
  }
}

export default BasicList;
